package controllers

import (
	"fmt"
	"github.com/flaravel/quanlaolao/app/models/promotion"
	"github.com/flaravel/quanlaolao/app/requests"
	"github.com/flaravel/quanlaolao/pkg/jssdk"
	"github.com/flaravel/quanlaolao/pkg/route"
	"github.com/flaravel/quanlaolao/pkg/types"
	"github.com/syyongx/php2go"
	"net/http"
)

type GroupPromotionController struct {
	BaseController
}

func (c GroupPromotionController) Show(w http.ResponseWriter, r *http.Request)  {
	id, err := types.IdDecode(route.GetRouteVariable("id", r))
	if err != nil {
		c.Error(w,"群信息不存在")
		return
	}
	_group , err := promotion.Get(types.Int64ToString(int64(id)))
	meAvatar := _group.GroupAvatars[0].Avatar
	avatarArr := _group.GroupAvatars[1:]
	var content []map[string]interface{}
	for _, v := range _group.GroupContents {
		contentValue := make(map[string]interface{})
		contentValue["content"] = v.Content
		contentValue["is_right"] = v.IsRight
		if v.IsRight == 1 {
			contentValue["avatar"] = meAvatar
		} else {
			if (len(avatarArr) > 0) {
				n := php2go.Rand(0,len(avatarArr) -1)
				contentValue["avatar"] = avatarArr[n].Avatar
			} else {
				contentValue["avatar"] = ""
			}

		}
		content = append(content,contentValue)
	}
	if err != nil {
		c.Error(w,"群信息不存在")
		return
	}
	contents := make(map[string]interface{})
	contents["group"] = _group
	contents["contents"] = content
	c.Success(w,contents)
}

func (c GroupPromotionController) Store(w http.ResponseWriter, r *http.Request)  {
	var errors map[string][]string
	group := promotion.GroupPromotion{
		Name:          r.PostFormValue("name"),
		Avatar:        r.PostFormValue("avatar"),
		WechatQrCode:  r.PostFormValue("wechat_qrcode"),
		Desc:          r.PostFormValue("desc"),
		Number:        types.StringToInt(r.PostFormValue("number")),
	}
	errors = requests.ValidateGroupForm(group)
	if len(errors) > 0 {
		for _, value := range errors {
			c.Error(w,value[0])
			return
		}
	}
	var avatarListStruct []promotion.GroupAvatar
	var contentsStruct []promotion.GroupContent
	avatarList := r.PostFormValue("avatarList")
	contents := r.PostFormValue("contents")
	_ = php2go.JSONDecode([]byte(avatarList),&avatarListStruct)
	_ = php2go.JSONDecode([]byte(contents),&contentsStruct)
	if len(avatarList) == 0 {
		c.Error(w,"请设置群聊头像")
		return
	}
	if len(contentsStruct) == 0 {
		c.Error(w,"请设置群聊记录")
		return
	}
	group.GroupAvatars = avatarListStruct
	group.GroupContents = contentsStruct
	_ = group.Create()
	if group.ID > 0 {
		// 创建访问链接
		group.Url = fmt.Sprintf("http://g.makepic.top/%s",types.IdEncode(int(group.ID)))
		_, _ = group.Update()
		c.Message(w,"创建成功")
	} else {
		c.Error(w,"创建失败")
	}
}


func (c GroupPromotionController) Jssdk(w http.ResponseWriter, r *http.Request) {
	path := r.PostFormValue("path")
	sign, err := jssdk.New(path)
	if err != nil {
		fmt.Println(err)
		c.Error(w,"微信分享异常")
		return
	}
	c.Success(w,sign)
}